<template>
    <el-dialog
        v-model="userSetRoleVisible"
        title="分配角色"
        @open="handleDialogOpen"
        @close="handleClose"
        draggable
    >
        <el-transfer
            v-model="selectedRoleIds"
            :data="data"
            :titles="['可选角色', '已选角色']"
            filter-placeholder="请输入角色名称"
            filterable
        />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import { getUserRoleIdList, setUserRole } from '@/api/system/user'
import { getRoleList } from '@/api/system/role'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const data = ref([]) // 存储角色列表的数据
const selectedRoleIds = ref([]) // 存储选中的角色ID
const userSetRoleForm = reactive({
    userId: undefined,
    roleIds: []
})
const { userSetRoleVisible, selectedRowId } = inject('userSetRole')
/**
 * 打开对话框
 */
function handleDialogOpen() {
    if (selectedRowId.value) {
        userSetRoleForm.userId = selectedRowId.value
        _getRoleList()
        getUserRoleIdList(userSetRoleForm.userId).then((response) => {
            if (response && response.data) {
                selectedRoleIds.value = response.data
            }
        })
    }
}
/**
 * 获取角色列表
 */
function _getRoleList() {
    getRoleList().then((response) => {
        if (response && response.data) {
            data.value = response.data.map((item) => {
                return {
                    key: item.id,
                    label: item.name,
                    disabled: item.status === 0 //0 禁用
                }
            })
        }
    })
}
/**
 * 提交表单
 */
function submitForm() {
    userSetRoleVisible.value = false
    // 更新表单中的角色ID数组
    userSetRoleForm.roleIds = selectedRoleIds.value
    setUserRole(userSetRoleForm)
    resetUserSetRoleForm()
    // 刷新表格
    const { query, path } = route
    router.replace({ path: '/redirect' + path, query: query })
}
// 重置 userSetRoleForm 的函数
const resetUserSetRoleForm = () => {
    Object.keys(userSetRoleForm).forEach((key) => {
        // 如果当前值是数组，则重置为空数组，否则设为 undefined
        userSetRoleForm[key] = Array.isArray(userSetRoleForm[key]) ? [] : undefined
    })
    selectedRoleIds.value = []
}
// 处理对话框关闭事件
function handleClose() {
    resetUserSetRoleForm()
    userSetRoleVisible.value = false
    selectedRoleIds.value = []
}
</script>
<style lang="scss" scoped></style>
